//
//  WBSendViewController.m
//  sinaWeibo
//
//  Created by 李江波 on 2016/11/22.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

#import "WBSendViewController.h"
#import "WBOAuthViewModel.h"

#import "LEEHTTPManager.h"
#import <SVProgressHUD.h>
#import "WBPhotoCollectionController.h"

#import "WBEmoticonKeyBoardView.h"
#import "WBEmoticon.h"
#import "WBTextAttachment.h"
#import "WBEmoticonManager.h"

#import <Masonry.h>
typedef enum : NSUInteger {
    composeButtonClickPhoto = 100,
    composeButtonClickMention,
    composeButtonClickTrend,
    composeButtonClickEmoticon,
    composeButtonClickAdd
} composeButtonClick;


@interface WBSendViewController ()<UITextViewDelegate>

@property(nonatomic ,strong) UIBarButtonItem *rightItem;

@property(nonatomic ,strong) UILabel *titleLable;

@property(nonatomic ,weak) UIStackView *stack;

@property(nonatomic ,weak) UITextView *textView;

/**
 占位文本
 */
@property(nonatomic ,strong) UILabel *placeLable;

@property(nonatomic ,strong) WBEmoticonKeyBoardView *keyBoardView;

@end

@implementation WBSendViewController

-(WBEmoticonKeyBoardView *)keyBoardView{

    if (nil == _keyBoardView) {
        //plus 键盘高度226 ， 其他为216
        _keyBoardView = [[WBEmoticonKeyBoardView alloc]initWithFrame:CGRectMake(0, 0, 0, 220)];
    }
    return _keyBoardView;
}

-(UIBarButtonItem *)rightItem{

    if (nil == _rightItem) {
        
        _rightItem = [UIBarButtonItem ItemWithbgimage:@"common_button_orange" bghighImage:@"common_button_orange_highlighted" bgdisableImage:@"common_button_white_disable" title:@"发送" target:self action:@selector(clickSend:)];
        //一开始设为禁用
        [_rightItem setEnabled: NO];
        
        
    }
    
    return _rightItem;
}

-(UILabel *)titleLable{

    if (nil == _titleLable) {
        
        _titleLable = [[UILabel alloc]init];
        
        _titleLable.numberOfLines = 0;
        _titleLable.textAlignment = NSTextAlignmentCenter;
        
        NSString *useName = [WBOAuthViewModel shared].userModel.name;
        NSString *str = @"发送微博\n";
        NSString *titleName = [str stringByAppendingString:useName];

        _titleLable.text = titleName;
        NSMutableAttributedString *attributStr = [[NSMutableAttributedString alloc]initWithString:titleName];
        
        NSRange range = [titleName rangeOfString:useName];
        [attributStr addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14], NSForegroundColorAttributeName : [UIColor orangeColor]} range:range];
        [_titleLable sizeToFit];
        _titleLable.attributedText = attributStr;
        
    }
    return _titleLable;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
}

-(void)setupUI{

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(clickClose)];
    
    self.navigationItem.rightBarButtonItem = self.rightItem;
    
    self.navigationItem.titleView = self.titleLable;
    
    [self setupTextView];
    [self setupStackView];
    [self setupPhotoCollection];
    
    [self.view bringSubviewToFront:self.stack];
    
    //监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emoticonBottonClick:) name:@"emoticonBottonClick" object:nil];
}

-(void)emoticonBottonClick:(NSNotification *)notification {

    if (notification.object == nil) {
        
        [self.textView deleteBackward];
    }else{
    
        WBEmoticon *emoticon = notification.object;
        if (emoticon.type) {
            //emoji表情
            [self.textView replaceRange:self.textView.selectedTextRange withText:emoticon.emojiStr];
            return;
        }
        
        WBTextAttachment *textAttachment = [[WBTextAttachment alloc]init];
        textAttachment.chs = emoticon.chs;
        NSBundle *bundle = [WBEmoticonManager shared].emoticonBundle;
    
        textAttachment.image = [UIImage imageNamed:emoticon.imagePath inBundle:bundle compatibleWithTraitCollection:nil];
        //设置bounds
        UIFont *font = self.textView.font;
        textAttachment.bounds = CGRectMake(0, -5, font.lineHeight, font.lineHeight);
        
        //2. 将附件对象包装富文本  不可变的属性文本是不能够添加属性的
        NSMutableAttributedString *imagetext = [[NSMutableAttributedString alloc]initWithAttributedString:[NSMutableAttributedString attributedStringWithAttachment:textAttachment]];
        
        //2.1 添加属性
        [imagetext addAttributes:@{NSFontAttributeName : font} range:NSMakeRange(0, 1)];
        //3. 获取textView的富文本 --> 可变的属性文本
        NSMutableAttributedString *strM = [[NSMutableAttributedString alloc]initWithAttributedString:self.textView.attributedText];
        
        //3.1 在替换之前 记录之前选中的range
        NSRange range = self.textView.selectedRange;
        
        //4. 向可变的富文本中插入 图片富文本
        [strM replaceCharactersInRange:self.textView.selectedRange withAttributedString:imagetext];
        //5. 将插入完成之后的富文本赋值 给textView.attributeText
        self.textView.attributedText = strM;
        //6.赋值结束之后恢复光标位置
        self.textView.selectedRange = NSMakeRange(range.location + 1, 0);
        
        //主动调用代理方法
        
        [self.textView.delegate textViewDidChange:self.textView];
    }
    
}

-(void)keyBoardChange:(NSNotification *)notifation{

    CGRect keyRect = [notifation.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//
    CGFloat H = -(kUISCRRENH - keyRect.origin.y);
    
    [self.stack mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(H);
    }];
    
    [UIView animateWithDuration:0.25 animations:^{
        
        [self.view layoutIfNeeded];
    }];
    
}

/**
 移除通知
 */
-(void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 设置textView
 */
-(void)setupTextView{

    UITextView *textView = [[UITextView alloc]init];
    textView.backgroundColor = [UIColor lightGrayColor];
    
    textView.font = [UIFont systemFontOfSize:18];
    
    [self.view addSubview:textView];
    
    _textView = textView;
    
    //textView可拖拽，并关闭键盘
    textView.alwaysBounceVertical = YES;
    textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    textView.delegate = self;
    
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.top.right.equalTo(self.view);
        make.height.offset(200);
    }];
    
    _placeLable = [[UILabel alloc]init];
    _placeLable.text = @"波波在此";
    _placeLable.textColor = [UIColor darkGrayColor];
    
    [textView addSubview:_placeLable];
    
    [_placeLable mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(textView).offset(8);
        make.left.equalTo(textView).offset(5);
    }];
    

}

#pragma mark : - textView代理方法
-(void)textViewDidChange:(UITextView *)textView{

    [self.rightItem setEnabled:textView.hasText];
    self.placeLable.hidden = textView.hasText;
}


/**
 设置StackView
 */
-(void)setupStackView {

    UIStackView *stack = [[UIStackView alloc]init];
    [self.view addSubview:stack];
    
    [stack mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.right.bottom.equalTo(self.view);
        make.height.offset(37);
    }];
    
    _stack = stack;
    //设置stackView参数
    stack.axis = UILayoutConstraintAxisHorizontal;
    stack.distribution = UIStackViewDistributionFillEqually;
    
    NSArray *btnNames = @[@"compose_toolbar_picture",
                           @"compose_mentionbutton_background",
                           @"compose_trendbutton_background",
                           @"compose_emoticonbutton_background",
                          @"compose_add_background"];
    
    for (int i = 0; i < btnNames.count; i ++) {
        
        UIButton *btn = [UIButton buttonWithType:0];
        [btn setImage:[UIImage imageNamed:btnNames[i]] forState:UIControlStateNormal];
        
        btn.tag = 100 + i;
        
        [btn addTarget:self action:@selector(clickComposeBotton:) forControlEvents:UIControlEventTouchUpInside];
        
        [btn setBackgroundColor:[UIColor colorWithWhite:0.9 alpha:1]];
        
        [stack addArrangedSubview:btn];
    }
    
}

#pragma mark : - 5个按钮点击
-(void)clickComposeBotton:(UIButton *)btn {

    switch (btn.tag) {
        case composeButtonClickPhoto:
            NSLog(@"照片");
            
            [[WBPhotoCollectionController shared] clickSelectPhotoButton];
            break;
        case composeButtonClickMention:
            NSLog(@"@");
            break;
        case composeButtonClickTrend:
            NSLog(@"话题");
            break;
        case composeButtonClickEmoticon:{
            NSLog(@"表情");
            //使用自定义键盘
            if (!_textView.isFirstResponder) {
                [_textView becomeFirstResponder];
            }
            
            self.textView.inputView = (self.textView.inputView == nil) ? self.keyBoardView : nil;
            
            [_textView reloadInputViews];
            
            break;
        }
            
        case composeButtonClickAdd:
            NSLog(@"更多");
            break;
        
    }
    
}

/**
 设置PhotoCollection
 */
-(void)setupPhotoCollection{

    WBPhotoCollectionController *photoVc = [WBPhotoCollectionController shared];
    
    [self.view addSubview:photoVc.view];
    [self addChildViewController:photoVc];
    [photoVc.view mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.textView.mas_bottom);
    }];
}

#pragma mark : - 一开始判断是否有图片
-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
        
    [WBPhotoCollectionController shared].collectionView.hidden = [WBPhotoCollectionController shared].images.count == 0;
    
}

-(void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
    
    [self.textView becomeFirstResponder];
}

#pragma mark : - 发送点击
-(void)clickSend:(UIBarButtonItem *)item {

    [item setEnabled: NO];
    
    NSString *urlStr = @"https://api.weibo.com/2/statuses/update.json";
    NSDictionary *parameters = @{@"access_token" : [WBOAuthViewModel shared].userModel.access_token,
                                 @"status" : [self imageEmoticon2Chs]};
    
    if ([WBPhotoCollectionController shared].images.count == 0) {
        //纯文本发送
        [[LEEHTTPManager manager] request:POST UrlString:urlStr parameters:parameters finshed:^(id responseObject, NSError *error) {
            
            if (error != nil) {
                [SVProgressHUD showErrorWithStatus:@"怎么就发送失败了，人品不好呢"];
                
                //发送失败把按钮解封
                [item setEnabled:YES];
                
                return ;
            }
            
            [SVProgressHUD showSuccessWithStatus:@"发送成功~真棒"];
            
            [self clickClose];
            
        }];
        
    } else {
        //单张图片上传
        urlStr = @"https://upload.api.weibo.com/2/statuses/upload.json";
        
        NSData *data = UIImagePNGRepresentation([WBPhotoCollectionController shared].images.firstObject);
        
        [[LEEHTTPManager manager] POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            [formData appendPartWithFileData:data name:@"pic" fileName:@"yeyeye" mimeType:@"application/octet-stream"];
            
        } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [SVProgressHUD showSuccessWithStatus:@"发送成功~真棒"];
            
            //成功后照片要清0
            [[WBPhotoCollectionController shared].images removeAllObjects];
            [[WBPhotoCollectionController shared].selectedAssets removeAllObjects];
            
            [self clickClose];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"%@",error);
            
            [SVProgressHUD showErrorWithStatus:@"怎么图片就发送失败了，人品不好呢"];
            
            //发送失败把按钮解封
            [item setEnabled:YES];
        }];
        
    }
    
}
#pragma mark : - 将图片表情转化成字符串
-(NSString *)imageEmoticon2Chs{
    //表情图片的属性中有 NSAttachment 对应的键值对 纯文本中就没有
    
    NSMutableString *str = [NSMutableString string];
    //遍历属性字符串的所有的属性
    [self.textView.attributedText enumerateAttributesInRange:NSMakeRange(0, self.textView.attributedText.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        
        WBTextAttachment *attachment = attrs[@"NSAttachment"];
        //完成字符串的拼接
        if (attachment) {
            NSLog(@"%@", attachment.chs);
            [str appendString:attachment.chs];
        }else{
        
            [str appendString:[self.textView.text substringWithRange:range]];
            NSLog(@"%@",str);
        }
    
    }];
    
    return str.copy;
}

#pragma mark : - 关闭控制器
-(void)clickClose {

    [self dismissViewControllerAnimated:YES completion:nil];
    
    [self.view endEditing:YES];
}

@end
